package com.example.onlineeducation.ui.main

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.ImageView
import androidx.activity.result.ActivityResultLauncher
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.onlineeducation.App
import com.example.onlineeducation.R
import com.example.onlineeducation.adapter.BannerAdapter
import com.example.onlineeducation.adapter.NoticeAdapter
import com.example.onlineeducation.base.BaseFragment
import com.example.onlineeducation.data.constant.ExamConstants
import com.example.onlineeducation.data.constant.StudyConstants
import com.example.onlineeducation.data.entity.BannerEntity
import com.example.onlineeducation.data.entity.StudyPlanEntity
import com.example.onlineeducation.data.json.BannerJson
import com.example.onlineeducation.data.json.ScanExamJson
import com.example.onlineeducation.databinding.MainHomeFragmentBinding
import com.example.onlineeducation.databinding.MainHomeStudyPlanItemBinding
import com.example.onlineeducation.ui.common.NoticeDetailActivity
import com.example.onlineeducation.ui.online.OnlineExaminationAc
import com.example.onlineeducation.ui.topic.StudyContentActivity
import com.example.onlineeducation.ui.topic.TopicGroupListActivity
import com.example.onlineeducation.viewmodel.MainHomeVM
import com.google.gson.Gson
import com.yc.jetpacklib.extension.*
import com.yc.jetpacklib.net.doFail
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.recycleView.YcRecyclerViewAdapter
import com.yc.jetpacklib.refresh.YcRefreshSpecialUtil
import com.yc.jetpacklib.release.YcSpecialViewSmart
import com.yc.jetpacklib.ui.YcScanQrcodeActivity
import com.yc.jetpacklib.utils.showErrorDialog
import com.yc.jetpacklib.widget.dialog.YcCommonDialog

class MainHomeFragment : BaseFragment<MainHomeFragmentBinding>(MainHomeFragmentBinding::inflate) {
    private val mViewModel: MainHomeVM by ycViewModels()
    private lateinit var mRefreshUtil: YcRefreshSpecialUtil
    private var mCurrentBannerItem = 0
    private var mBannerList = mutableListOf<BannerEntity>()
    private var mProId: String? = null
    private var isPlayBanner = false
    private lateinit var scanQrcodeLauncher: ActivityResultLauncher<Intent>
    private val dialog by lazy {
        YcCommonDialog(requireContext(), this)
    }
    private val scanResultDialog by lazy {
        YcCommonDialog(requireContext(), this, isCancelable = true)
    }
    private val mBannerAdapter by lazy {
        BannerAdapter().apply {
            mItemClick = { entity ->
                if (!entity.showDefault) {
                    NoticeDetailActivity.newInstance(
                        requireActivity(),
                        entity.imgName,
                        true,
                        imgUrl = entity.imgUrl
                    )
                    //WebPreviewActivity.newInstance(requireActivity(), entity.jumpAddress)
                }
            }
        }
    }

    private val mNoticeAdapter by lazy {
        NoticeAdapter().apply {
            mItemClick = { entity ->
                NoticeDetailActivity.newInstance(
                    requireActivity(),
                    entity.name,
                    false,
                    content = entity.content
                )
                //WebPreviewActivity.newInstance(requireActivity(), entity.url)
            }
        }
    }

    private val mStudyPlanAdapter by YcRecyclerViewAdapter.ycLazyInitApply<StudyPlanEntity, MainHomeStudyPlanItemBinding>(
        MainHomeStudyPlanItemBinding::inflate
    ) {
        mOnUpdate = { item ->
            ivTopic.ycLoadImageNet(item.imgUrl, errorImg = R.drawable.ic_topic)
            tvTopicName.text = item.groupName
            tvTopicTime.text = item.getTimeRange()//获取时间范围
            tvState.text = StudyConstants.showProgressText(item.topicStudyStatus)
            tvState.ycSetTextColorRes(StudyConstants.showProgressTextColor(item.topicStudyStatus))
            ivState.setImageResource(StudyConstants.showProgressIcon(item.topicStudyStatus))
        }
        mItemClick = { item ->
            if (item.groupId.ycIsNotEmpty())
                TopicGroupListActivity.newInstance(
                    requireActivity(),
                    item.groupId!!,
                    item.groupName
                )
            else
                showToast("专题分组id不为空，请联系管理员")
        }
    }

    override fun MainHomeFragmentBinding.initView(view: View, savedInstanceState: Bundle?) {
        rvBanner.apply {
            adapter = mBannerAdapter
            layoutManager = LinearLayoutManager(
                requireActivity(),
                RecyclerView.HORIZONTAL,
                false
            ) //反向reverseLayout=true从最后一个item显示
            //这个方法是关键：LinearSnapHelper可以帮助Android的RecyclerView实现滚轮效果，所谓滚轮效果，就是在列表内容滚动时候，总是把某一项内容处于屏幕（视野）正中间。
            val mLinearSnapHelper = LinearSnapHelper()
            mLinearSnapHelper.attachToRecyclerView(this)
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    val first =
                        (recyclerView.layoutManager as LinearLayoutManager?)!!.findFirstVisibleItemPosition()
                    val last =
                        (recyclerView.layoutManager as LinearLayoutManager?)!!.findLastVisibleItemPosition()
                    if (mCurrentBannerItem != (first + last) / 2) {
                        mCurrentBannerItem = (first + last) / 2
                        addBottomDots(mCurrentBannerItem)
                    }
                }
            })
        }
        marqueeViewNotice.setAdapter(mNoticeAdapter)
        rvList.adapter = mStudyPlanAdapter
        srlList.setNoMoreData(true)
        mRefreshUtil = YcRefreshSpecialUtil(
            requireActivity(),
            srlList,
            mStudyPlanAdapter,
            YcSpecialViewSmart(rvList, flRefresh),
            false
        )
        mRefreshUtil.mRefreshAndLoadMore = { isRefresh: Boolean, _: Int, _: Int ->
            if (isRefresh) {
                getData()
            }
        }
        tvSearch.setOnClickListener {
            MainHomeSearchActivity.newInstance(requireActivity())
        }
        ivScan.setOnClickListener {
            YcScanQrcodeActivity.newInstance(
                requireActivity(),
                scanQrcodeLauncher,
                R.drawable.shape_bg_scan_qrcode_frame
            )
        }
        scanQrcodeLauncher = ycCreateResultLauncher {
            if (it.data != null) {
                val result: String = it.data?.getStringExtra(YcScanQrcodeActivity.SCAN_RESULT) ?: ""
                if (result.ycIsEmpty()) {
                    showErrorDialog(dialog, "扫描结果为空，请再试一次")
                    return@ycCreateResultLauncher
                } else {
                    try {
                        var mScanExamJson: ScanExamJson =
                            Gson().fromJson(result, ScanExamJson::class.java)
                        mViewModel.getExamInfoAndTopicInfo(
                            mScanExamJson.examId,
                            mScanExamJson.topicId,
                            mProId!!
                        )
                    } catch (e: Exception) {
                        showToast("二维码有误请重试!")
                    }


                }
            }
        }
        App.mInstant.mViewModel.mProInfoEntity.observe {
            if (it != null && mProId != it.proId) {
                mProId = it.proId
                getData()
            }
        }
        mViewModel.mBannerListDataModel.observe { ycResult ->
            ycResult.doSuccess {
                setBannerList(it)
            }.doFail {
                setBannerList(null)
            }
        }
        mViewModel.mNoticeListDataModel.observe { ycResult ->
            ycResult.doSuccess {
                if (it.ycIsNotEmpty()) {
                    mNoticeAdapter.setDataList(it!!)
                    marqueeViewNotice.startFlipping()
                    marqueeViewNotice.visibility = View.VISIBLE
                } else {
                    marqueeViewNotice.visibility = View.INVISIBLE
                    marqueeViewNotice.stopFlipping()
                }
            }.ycShowNetError()
        }
        mViewModel.mStudyPlanList.observe {
            it.doSuccess { data ->
                mStudyPlanAdapter.addAllData(data)
            }.ycShowNetError()
            mRefreshUtil.ycRefreshAndLoadMoreResult(it)
        }
        mViewModel.mExamInfoAndTopicInfoDataModel.observe {
            it.doSuccess {
                if (it.topicId.ycIsNotEmpty() && it.examId.ycIsNotEmpty()) {
                    scanResultDialog.apply {
                        setTitle("考试信息")
                        setMsg("考试名:" + it.examName + "\n" + "考试时长:" + it.time + "分钟")
                        setRightBtnText("去考试")
                        setLeftBtnText("去学习")
                        setOnRightClick {
                            if (!it.examPass.equals(ExamConstants.PASSED)) {
                                if (it.isExceedTime) {
                                    mViewModel.getCheckStudyTime(mProId!!, it.topicId, it)
                                } else {
                                    dialog.setMsg("考试已结束").showSingle()
                                }
                            } else {
                                dialog.setMsg("考试已通过").showSingle()
                            }
                        }
                        setOnLeftClick {
                            StudyContentActivity.newInstance(
                                requireActivity(),
                                it.topicId,
                                it.needStudyTime,
                                it.topicStudyTime
                            )
                        }
                        show()
                    }
                } else {
                    showToast("未查询到相关考试，请重试!")
                }
            }.ycShowNetError()
        }
        mViewModel.mCheckStudyTimeDataModel.observe {
            it.doSuccess {
                OnlineExaminationAc.newInstance(
                    requireContext(), it.examId, it.examName, it.time, it.timeEnd
                )
            }.ycShowNetError()
        }
    }

    private fun MainHomeFragmentBinding.setBannerList(it: List<BannerEntity>?) {
        if (it.ycIsNotEmpty()) {
            mBannerList = (it as MutableList<BannerEntity>?)!!
            mBannerAdapter.addAllData(mBannerList)
            if (mBannerList.size == 1) {
                setPlayBanner(false)
            } else {
                setPlayBanner(true)
            }
        } else {
            val entity = BannerEntity("", "", "", "", 0)
            entity.showDefault = true
            mBannerList = mutableListOf(entity)
            mBannerAdapter.addAllData(mBannerList)
            setPlayBanner(false)
        }
        mCurrentBannerItem = 0
        rvBanner.scrollToPosition(mCurrentBannerItem)
        addBottomDots(mCurrentBannerItem)
    }

    private fun getData() {
        mViewModel.getBanner(mProId!!)
        mViewModel.getNotice(mProId!!)
        mViewModel.getStudyPlanList(mProId!!)
    }

    private fun MainHomeFragmentBinding.addBottomDots(currentPage: Int) {
        val dots = arrayOfNulls<ImageView>(mBannerList.size)
        if (llDots.childCount > 0) {
            llDots.removeAllViews()
        }
        for (i in mBannerList.indices) {
            dots[i] = ImageView(requireContext())
            dots[i]?.setPadding(5, 0, 5, 0)
            if (i == currentPage) {
                dots[i]?.setImageResource(R.drawable.shape_oval_dot_green)
            } else {
                dots[i]?.setImageResource(R.drawable.shape_oval_dot_grey)
            }
            llDots.addView(dots[i])
        }
    }

    override fun onStop() {
        super.onStop()
        setPlayBanner(false) // 停止轮播
    }

    private fun setPlayBanner(playing: Boolean) {
        if (!isPlayBanner && playing) {
            mHandler.postDelayed(viewPageTask, 6000)
            isPlayBanner = true
        } else if (isPlayBanner && !playing) {
            mHandler.removeCallbacksAndMessages(null)
            isPlayBanner = false
        }
    }

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        //主线程：接收子线程传递过来的数据，并进行处理
        override fun handleMessage(msg: Message) {
            mViewBinding.apply {
                if (mCurrentBannerItem == 0) {
                    rvBanner.scrollToPosition(mCurrentBannerItem) //快速滑动
                    addBottomDots(mCurrentBannerItem)
                } else {
                    rvBanner.smoothScrollToPosition(mCurrentBannerItem) //平滑滑动:有动画过度
                }
            }
        }
    }

    private val viewPageTask: Runnable by lazy {
        object : Runnable {
            override fun run() {
                if (mBannerList.ycIsNotEmpty()) {
                    mHandler.postDelayed(this, 6000)
                    mCurrentBannerItem = (mCurrentBannerItem + 1) % mBannerList.size
                    mHandler.sendEmptyMessage(0)
                }
            }
        }
    }
}
